package org.jeecg.modules.basicSku.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.basicSku.entity.BasicSku;
import org.jeecg.modules.basicSku.service.IBasicSkuService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 品番表
 * @Author: jeecg-boot
 * @Date:   2024-06-26
 * @Version: V1.0
 */
@Api(tags="品番表")
@RestController
@RequestMapping("/basicSku/basicSku")
@Slf4j
public class BasicSkuController extends JeecgController<BasicSku, IBasicSkuService> {
	@Autowired
	private IBasicSkuService basicSkuService;
	
	/**
	 * 分页列表查询
	 *
	 * @param basicSku
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "品番表-分页列表查询")
	@ApiOperation(value="品番表-分页列表查询", notes="品番表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(BasicSku basicSku,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<BasicSku> queryWrapper = QueryGenerator.initQueryWrapper(basicSku, req.getParameterMap());
		Page<BasicSku> page = new Page<BasicSku>(pageNo, pageSize);
		IPage<BasicSku> pageList = basicSkuService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param basicSku
	 * @return
	 */
	@AutoLog(value = "品番表-添加")
	@ApiOperation(value="品番表-添加", notes="品番表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody BasicSku basicSku) {
		basicSkuService.save(basicSku);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param basicSku
	 * @return
	 */
	@AutoLog(value = "品番表-编辑")
	@ApiOperation(value="品番表-编辑", notes="品番表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody BasicSku basicSku) {
		basicSkuService.updateById(basicSku);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "品番表-通过id删除")
	@ApiOperation(value="品番表-通过id删除", notes="品番表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		basicSkuService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "品番表-批量删除")
	@ApiOperation(value="品番表-批量删除", notes="品番表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.basicSkuService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "品番表-通过id查询")
	@ApiOperation(value="品番表-通过id查询", notes="品番表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		BasicSku basicSku = basicSkuService.getById(id);
		if(basicSku==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(basicSku);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param basicSku
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BasicSku basicSku) {
        return super.exportXls(request, basicSku, BasicSku.class, "品番表");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, BasicSku.class);
    }

	 @RequestMapping(value = "/supplement", method = RequestMethod.POST)
	 public Result<?> supplement(HttpServletRequest request, HttpServletResponse response) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		 for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			 MultipartFile file = entity.getValue();// 获取上传文件对象
			 ImportParams params = new ImportParams();
			 params.setTitleRows(2);
			 params.setHeadRows(1);
			 params.setNeedSave(true);
			 try {
				 List<BasicSku> list = ExcelImportUtil.importExcel(file.getInputStream(), BasicSku.class, params);
				 List<String> skuCode = list.stream()
						 .map(BasicSku::getSkuCode)
						 .map(sku -> sku.substring(0, sku.indexOf("-") + 4))
						 .collect(Collectors.toList());
				 Map<String, BasicSku> map = list.stream()
						 .collect(Collectors.toMap(
								 sku -> sku.getSkuCode().substring(0, sku.getSkuCode().indexOf("-") + 4), // 键为 skuCode
								 Function.identity(), // 值为 BasicSku 实例自身
								 (oldValue, newValue) -> oldValue // 保留旧值，忽略新值
						 ));
				 LambdaQueryWrapper<BasicSku> wrapper = Wrappers.lambdaQuery();
				 wrapper.in(BasicSku::getSkuCode, skuCode);
				 List<BasicSku> skuList = basicSkuService.list(wrapper);
				 for (BasicSku sku : skuList) {
					 if (map.containsKey(sku.getSkuCode())) {
						 BasicSku sku1 = map.get(sku.getSkuCode());
						 sku.setLength(sku1.getLength()).setWidth(sku1.getWidth())
								 .setHeight(sku1.getHeight());
					 } else {
						 log.info("不存在的sku： {}", sku.getSkuCode());
					 }
				 }
				 basicSkuService.updateBatchById(skuList);
				 return Result.ok("文件导入成功！数据行数：" + list.size());
			 } catch (Exception e) {
				 log.error(e.getMessage(), e);
				 return Result.error("文件导入失败:" + e.getMessage());
			 } finally {
				 try {
					 file.getInputStream().close();
				 } catch (IOException e) {
					 e.printStackTrace();
				 }
			 }
		 }
		 return Result.error("文件导入失败！");
	 }

}
